#include <stdio.h>
#include "btree.h"
#include "input.h"

extern BTREE* recreate_tree(char **code_table)
{
    /* This variable holds the number of loop iterations for the first loop
     * later down the code*/
    int i;
    /* This variable holds the number of loop iterations for the second loop
     * later down the code*/
    int j;
    int code_length;
    char* code;
    char digit;
    BTREE_NODE *current_node;
    BTREE_NODE *new_node;

    BTREE* code_tree = btree_new(0, 0, 0, 0);
    current_node = btree_get_root(code_tree);

    /* Iterate over code table*/

    for (i = 0; i < ANSI_COUNT; ++i)
    {
        /* Now, iterate over code */
        code = code_table[i];
        if (code == 0) {
            continue;
        }
        code_length = strlen(code);
        for (j = 0; j < code_length; ++j)
        {
            digit = code[j];
            if (digit == '1')
            {
                /* it's just a jump to the left */
                if (!btreenode_get_left(current_node))
                {
                    new_node = btreenode_new('\0');
                    btreenode_set_left(current_node, new_node);
                }
                current_node = btreenode_get_left(current_node);
            }
            else if (digit == '0')
            {
                /* and then a step to the rii-ii-i-ight */
                if (!btreenode_get_right(current_node))
                {
                    new_node = btreenode_new('\0');
                    btreenode_set_right(current_node, new_node);
                }
                current_node = btreenode_get_right(current_node);
            }
            else
            {
                printf("Ooops! That shouldn't have happend. "
                       "A '%c' screwed up our dearest of all code tables.",
                       digit);
            }
        }

        /* another code against the gone */
        btreenode_set_data(current_node, (char)i);

        /* reset current node for next code */
        current_node = btree_get_root(code_tree);
    }

    return code_tree;
}
